#include "transparency.h"
#include "scene.h"
#include "lightfrustum.h"
#include "textures.h"
#include "reflection.h"

using namespace Scene;
using namespace Textures;

namespace Transparency
{

vector4 plane_0,
		plane_1L,
		plane_1R,
		plane_2;

void init()
{
	plane_0 = vector4(.0f,.0f,1.0f,-(table_pos.z+table_h-table_top_h)),
	plane_1L = vector4(.0f,.0f,1.0f,-(table_pos.z+table_h)),
	plane_1R = vector4(.0f,1.0f,.0f,-(table_pos.y)),
	plane_2 = vector4(1.0f,.0f,.0f,-(table_pos.x));
}

void draw_table_leg(int i)
{
	glPushMatrix();
	glRotatef(90.0f*i,.0f,.0f,1.0f);
	glCallList(table_leg);
	glPopMatrix();
}

void draw_table_legs()
{
	draw_table_leg(0);
	draw_table_leg(1);
	draw_table_leg(2);
	draw_table_leg(3);
}

void draw_table_surface()
{
	glPushAttrib(GL_ALL_ATTRIB_BITS);
	glActiveTexture(GL_TEXTURE0);
	glEnable(GL_TEXTURE_2D);
	glBindTexture(GL_TEXTURE_2D, tex_reflect);

	glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_COMBINE);
	glTexEnvi(GL_TEXTURE_ENV, GL_COMBINE_RGB, GL_MODULATE);
	glTexEnvi(GL_TEXTURE_ENV, GL_SRC0_RGB, GL_TEXTURE);
	glTexEnvi(GL_TEXTURE_ENV, GL_OPERAND0_RGB, GL_SRC_COLOR);
	glTexEnvi(GL_TEXTURE_ENV, GL_SRC1_RGB, GL_PREVIOUS);
	glTexEnvi(GL_TEXTURE_ENV, GL_OPERAND1_RGB, GL_SRC_COLOR);
	glTexEnvi(GL_TEXTURE_ENV, GL_COMBINE_ALPHA, GL_REPLACE);
	glTexEnvi(GL_TEXTURE_ENV, GL_SRC0_ALPHA, GL_PREVIOUS);
	glTexEnvi(GL_TEXTURE_ENV, GL_OPERAND0_ALPHA, GL_SRC_ALPHA);

	Reflection::reflection_mapping();
	glDisable(GL_CULL_FACE);
	glCallList(table_top);
	glEnable(GL_CULL_FACE);
	glDisable(GL_TEXTURE_GEN_S);
	glDisable(GL_TEXTURE_GEN_T);
	glDisable(GL_TEXTURE_GEN_R);
	glDisable(GL_TEXTURE_GEN_Q);
	glMatrixMode(GL_TEXTURE);
	glLoadIdentity();
	glMatrixMode(GL_MODELVIEW);
	glPopAttrib();
}

void draw_table_top()
{
	glCallList(table_side);
	draw_table_surface();
}

void draw_table()
{
	glPushAttrib(GL_ALL_ATTRIB_BITS);
	glColor4f(0.4f,0.4f,0.4f,1.0f);
	glPushMatrix();
	glTranslatef(table_pos.x, table_pos.y, table_pos.z);

	draw_table_legs();
	draw_table_top();

	glPopMatrix();
	glPopAttrib();
}

void render_transparent_objects(bool mirror)
{
	draw_table();
	LightFrustum::render(mirror);
}

}